package jinyilw.swing.visuals;

import jinyilw.swing.ColorTools;
import jinyilw.swing.ComponentTools;
import jinyilw.swing.graphics.RenderingConfig;
import jinyilw.swing.rlaf.theme.RRootPaneSet;
import jinyilw.swing.rlaf.theme.RThemeColor;

import javax.swing.JRootPane;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TransRootPane extends JRootPane
{
	private static final long serialVersionUID = 7854431120368300425L;
	private static final AlphaComposite alphaComposite = ComponentTools.alphaComposite;
	private static RRootPaneSet rootPaneSet;
	public static final int arc = 8;
	private float alpha = 0.8f;
	private int opacity = 180;
	private boolean isActive;
	private final RenderingConfig renderingConfig = new RenderingConfig();

	public TransRootPane(Window window)
	{
		if (rootPaneSet == null)
			rootPaneSet = RRootPaneSet.getRootPaneSet();
		window.addWindowListener(new WindowHandler());
	}

	public void setAlpha(float alpha)
	{
		this.alpha = alpha;
	}

	public void setColorOpacity(int opacity)
	{
		this.opacity = opacity;
	}

	@Override
	public void updateUI()
	{
	}

	@Override
	public void setWindowDecorationStyle(int windowDecorationStyle)
	{
	}

	@Override
	protected void paintComponent(Graphics g)
	{
		int width = this.getWidth(), height = this.getHeight();
		Graphics2D g2d = (Graphics2D) g;
		Composite composite = g2d.getComposite();
		g2d.setComposite(alphaComposite.derive(alpha));
		g2d.drawImage(rootPaneSet.bgImage, 0, 0, width, height, null);
		g2d.setComposite(composite);
		if (opacity > 10 && opacity <= 255)
		{
			g2d.setColor(
					ColorTools.getAlphaColor(rootPaneSet.bgColor, opacity));
			g2d.fillRect(0, 0, width, height);
		}
		if (isActive)
		{
			renderingConfig.setAAPainting(g2d);
			g2d.setColor(RThemeColor.windowBorderColor);
			int ar = arc + 3;
			g2d.drawRoundRect(0, 0, width - 1, height - 1, ar, ar);
			renderingConfig.resetAAPainting(g2d);
		}
	}

	class WindowHandler extends WindowAdapter
	{
		@Override
		public void windowActivated(WindowEvent ev)
		{
			isActive = true;
			repaint();
		}

		@Override
		public void windowDeactivated(WindowEvent ev)
		{
			isActive = false;
			repaint();
		}
	}
}
